<?php
/**
 * Description for Featured Area Model
 *
 * @author Pavel Savchuk
 */
class Default_Model_FeaturedareaModel extends RCMS_Core_BaseModel {

	protected $_faTableName = 'featured_area';
	protected $_pageTableName = 'page';
    protected $_tablePageHasFa = 'page_has_fa';

	/**
	 *Selects all featured areas
	 * @return <array>
	 */
	public function  selectAllFeaturedAreas()
    {
		$select = $this->_adapter->select()
			->from(array('featured_area' => 'featured_area'), array('id' => 'id',	'name' => 'name', 'order' => 'order'))
			->joinLeft(array('page_has_fa'=>'page_has_fa'),	'featured_area.id = page_has_fa.fa_id')
			->joinLeft(array('page' => 'page'), 'page_has_fa.page_id = page.id', array('pages' => 'count(page.id)'))
			->group('featured_area.id');
		//return $this->_adapter->fetchAll($select);
		return $this->_adapter->fetchAll($select, null, Zend_Db::FETCH_ASSOC);
	}
	/**
	 *Selects featured area by name
	 * @param string $name
	 * @return <array>
	 */
	public function  selectFeaturedAreaByName($name)
    {
		$select = $this->_adapter->select()->from('featured_area')->where('name = ?',$name);
		return $this->_adapter->fetchOne($select);
	}

	/**
	 *Inserts featured area
	 * @param <string> $name
	 * @return <integer>
	 */
	public function inserFeaturedArea($name)
    {
		$this->_adapter->insert($this->_faTableName, array('name' => $name));
		return $this->_adapter->lastInsertId($this->_faTableName);
	}

    /**
     * selects all data for fa
     * @param <integer> $id
     * @return <array>
     */
    public function selectOrdersForFa($id)
    {
        $select = $this->_adapter->select()
                ->from($this->_tablePageHasFa)
                ->join($this->_pageTableName, $this->_tablePageHasFa.'.page_id = '.$this->_pageTableName.'.id', array('nav_name'))
                ->where("fa_id = ?", $id)->order(array('order'));
        return $this->_adapter->fetchAll($select);
    }

    /**
     * updates order of page for fa
     * @param <integer> $faID
     * @param <integer> $pageID
     * @param <integer> $index
     * @return <integer> or (boolean) false if query failed
     */
    public function updateOrdersForFa($faID, $pageID, $index)
    {
        return $this->_adapter->update($this->_tablePageHasFa, array('order' => $index), "page_id = $pageID AND fa_id = $faID");
    }

}
